import numpy as np
import cv2
font_scale=1.5 #字体大小
font=cv2.FONT_HERSHEY_PLAIN#字体类型

sum=np.load('sum.npy')
shape=np.load('shape.npy')

def normalize(data):  # 将图片像素二值化
    m, n = data.shape
    for i in range(m):
        for j in range(n):
            if data[i, j] >200:  # 位置有像素即为1
                data[i, j] = 1
            else:
                data[i, j] = 0
    return data

def predict(sum,shape,test):
    '''
    :param sum: 10
    :param shape: 10* (28*28)
    :param test: 28*28
    :return:
    '''
    test=np.array(test).reshape(-1)
    dimsnum=test.shape[0]
    ans = 1
    mark=-1
    max=0
    for k in range(10):
        for j in range(0, dimsnum):  # dimsnum维
            if test[j] == 1:  # 第i个图片的第j维对应为1 '出现此概率'
                ans *= shape[k][j]
            else:  # 未出现
                ans *= (1 - shape[k][j])
        ans *= sum[k]
        if max<ans:
            max=ans
            mark=k
        ans=1
    return mark




cap=cv2.VideoCapture('2021-04-04_182439.mp4')
if not cap.isOpened():
    cap=cv2.VideoCapture(0)
if not cap.isOpened():
    raise IOError('Can not open video')
print(sum,shape)
text='Some text in a box!'
#获得box的长和宽
(text_width,text_height)=cv2.getTextSize(text,font,fontScale=font_scale,thickness=1)[0]
#设置box的开始位置
text_offset_x=10
text_offset_y=10
#设置box的坐标
box_coords=((text_offset_x,text_offset_y),(text_offset_x+text_width+2,text_offset_y-text_height-2))
cntr=0;
while True:
    ret,frame=cap.read()
    cntr=cntr+1
    if(True):#(cntr%2)==0
        gray=cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)#先将彩图转化为灰度图
        gray=cv2.dilate(gray, None, iterations=2)
        gray = cv2.erode(gray, None, iterations=2)
        resized=cv2.resize(gray,(28,28),interpolation=cv2.INTER_AREA)#调整输入图片的尺寸
        resized=normalize(resized)
        status=predict(sum,shape,resized)
        x1,y1,w1,h1=0,0,175,75
        #画绿色的矩形
        cv2.rectangle(frame,(x1,x1),(x1+w1,y1+h1),(0,255,0),-1)
        #add text
        cv2.putText(frame,str(status),(x1+int(w1/5),y1+int(h1/2)),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2)
        cv2.imshow('handwritten Digits Recognition Test',frame)
        if cv2.waitKey(2) & 0xFF==ord('q'):
            break
cap.replease()
cv2.destroyAllwimdows()
